// cloudfunctions/login/index.js
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

/**
 * 用户登录云函数
 */
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { userInfo } = event

  try {
    // 获取用户openid
    const openid = wxContext.OPENID

    if (!openid) {
      return {
        success: false,
        code: 1003,
        message: '获取用户身份失败'
      }
    }

    // 查询用户是否已存在
    const userQuery = await db.collection('users').where({
      _openid: openid
    }).get()

    let userData

    if (userQuery.data.length === 0) {
      // 新用户，创建用户记录
      const createTime = new Date()
      const newUser = {
        _openid: openid,
        openid: openid,
        nickName: userInfo.nickName || '用户',
        avatarUrl: userInfo.avatarUrl || '',
        gender: userInfo.gender || 0,
        country: userInfo.country || '',
        province: userInfo.province || '',
        city: userInfo.city || '',
        createTime: createTime,
        lastLoginTime: createTime,
        updateTime: createTime,
        settings: {
          monthlyBudget: 5000,
          currency: 'CNY',
          theme: 'light',
          notifications: true,
          language: 'zh-CN',
          autoBackup: true,
          budgetAlert: true,
          alertThreshold: 80
        },
        statistics: {
          totalBills: 0,
          totalIncome: 0,
          totalExpense: 0,
          lastBillDate: '',
          activeDays: 0
        }
      }

      const createResult = await db.collection('users').add({
        data: newUser
      })

      userData = {
        ...newUser,
        _id: createResult._id
      }

      console.log('新用户注册成功:', openid)
    } else {
      // 老用户，更新登录时间和用户信息
      userData = userQuery.data[0]
      
      const updateData = {
        lastLoginTime: new Date(),
        updateTime: new Date()
      }

      // 更新用户信息（如果有变化）
      if (userInfo.nickName && userInfo.nickName !== userData.nickName) {
        updateData.nickName = userInfo.nickName
      }
      if (userInfo.avatarUrl && userInfo.avatarUrl !== userData.avatarUrl) {
        updateData.avatarUrl = userInfo.avatarUrl
      }

      await db.collection('users').doc(userData._id).update({
        data: updateData
      })

      // 更新本地数据
      Object.assign(userData, updateData)

      console.log('用户登录成功:', openid)
    }

    return {
      success: true,
      code: 0,
      message: '登录成功',
      data: {
        openid: openid,
        userInfo: userData
      }
    }

  } catch (error) {
    console.error('登录失败:', error)
    return {
      success: false,
      code: 5001,
      message: '登录失败，请重试',
      error: error.message
    }
  }
}